﻿@using PMS.Web.Models.SystemModules
@{
    Layout = "_AdminHomeLayout";
}
@model SystemModuleModel
@section CssStyles{
<style type="text/css">
    .systemauthorizemanage {
        width: 100%;
        height: 100%;
        background-color: #fff;
        margin: 0;
        padding: 10px 0;
        position: absolute;
    }
    .ew-tree-table { margin: 0 auto !important; }
</style>
}
<div class="systemauthorizemanage">
    <div class="layui-container layui-col-220" style="padding: 0;">
        <div class="layui-nav-custom-title">@ViewBag.PageTitle</div>
        <div id="organizetree" class="layui-row layui-nav-custom-content organizetree"></div>
    </div>
    <div class="layui-container layui-col-220 l220" style="padding: 0;">
        <div class="layui-nav-custom-title">角色列表</div>
        <div id="roleslist" class="layui-row layui-nav-custom-content roleslist"></div>
    </div>
    <div id="rightpanel" class="right-col-body l440" style="margin: 0 5px;">
        <form class="layui-form">
            <table id="pms-table" lay-filter="pms-table"></table>
        </form>
    </div>
</div>
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = Model.Id, position = ModuleButtonGroup.HeadButtonsGroup })
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = Model.Id, position = ModuleButtonGroup.RecordButtonsGroup })
<script id="roleslistTpl" type="text/html">
    <ul class="list-items">
        {{#  layui.each(d, function(index, item){ }}
        <li class="list-item">
            <a href="javascript:;" data-id="{{item.Id}}">
                {{ item.DisplayName }}
                {{#  if(item.IsAdmin){ }}
                <span class="layui-badge-dot toolgroup" data-tips="系统管理员"></span>
                {{#  } }}
            </a>
        </li>
        {{#  }); }}
        {{#  if(d.length === 0){ }}
        无数据
        {{#  } }}
    </ul>
</script>
<script type="text/html" id="viewPermissionTpl">
    <input type="checkbox" name="viewpermission" value="{{d.IsActive}}" data-id="{{d.Id}}" data-pid="{{d.ParentModuleId}}" lay-filter="systemmoduleauthorize" lay-skin="switch" lay-text="ON|OFF" {{ d.IsActive ? 'checked' : '' }} />
</script>
@section Scripts{
    <script type="text/javascript">
        layui.use(['form', 'element', 'jquery', 'tree', 'loading', 'http', 'laytpl', 'treeTable2', 'popup', 'lodash'], function () {
            let element = layui.element,
                tree = layui.tree,
                form = layui.form,
                $ = layui.jquery,
                loading = layui.loading,
                http = layui.http,
                laytpl = layui.laytpl,
                treeTable = layui.treeTable2,
                popup = layui.popup,
                lodash = layui.lodash;

            let cachedroleModels = [];
            let initPageComponents = function () {
                //组织机构树
                http.get(backendwebapiConfig.loadorganizelist, null,
                    function () { //beforeSend
                        loading.block({ type: 1, elem: '.organizetree', msg: '加载中...' })
                    }
                ).done(function (response) {
                    if (response.state && response.state === 200) {
                        let organizes = response.data;
                        if (PMSUtils.isString(organizes))
                            organizes = $.parseJSON(response.data);
                        tree.render({
                            elem: "#organizetree",
                            onlyIconControl: true,
                            data: PMSUtils.toArrayTree(organizes, { strict: true, parentKey: 'parentid', key: 'id', children: 'children', sortKey: 'displayorder' }),
                            click: function (obj) {
                                initRolesList(obj.data.parentid);
                            }
                        });
                    }
                }).fail(function (error) {
                    http.ajax.logError(error);
                }).always(function () {
                    loading.blockRemove(".organizetree", 1000); //CSS Selector
                });

                let initRolesList = function (organizeId) {
                    if (cachedroleModels.length === 0) {
                        http.get(backendwebapiConfig.loadadminroleslist, null,
                            function () { //beforeSend
                                loading.block({ type: 1, elem: '.roleslist', msg: '加载中...' })
                            }
                        ).done(function (response) {
                            if (response.state && response.state === 200) {
                                cachedroleModels = response.data;
                                initRolesList(organizeId);
                            }
                        }).fail(function (error) {
                            http.ajax.logError(error);
                        }).always(function () {
                            loading.blockRemove(".roleslist", 1000);
                        });
                    } else {
                        const roleTpl = document.getElementById("roleslistTpl").innerHTML;
                        let rolesdata = lodash.filter(cachedroleModels, ['FKOrganizeId', organizeId]);
                        laytpl(roleTpl).render(rolesdata, function (html) {
                            $("#roleslist").html(html);
                        });
                    }
                };
            };

            initPageComponents();

            let buttons = [],
                authorizeTableIns = null,
                authorizetreetableconfig = {
                    elem: '#pms-table',
                    tree: {
                        iconIndex: 1,               // 折叠图标显示在第几列
                        idName: 'Id',               // 自定义id字段的名称
                        pidName: 'ParentModuleId',  // 自定义标识是否还有子节点的字段名称
                        isPidData: true  // 是否是pid形式数据
                    },
                    toolbar: '#pmsHeadbarTpl',
                    cols: [
                        { field: 'Id', title: 'ID', width: 50 },
                        { field: 'DisplayName', title: '名称', width: 280 },
                        { field: 'IsActive', title: '模块权限', templet: '#viewPermissionTpl', align: 'center', width: 130 },
                        {
                            title: '模块操作权限',
                            templet: function (d) {
                                if (d.ModuleAssignedButtonIds.length > 0) {
                                    let outputHtml = '';
                                    const assignedBtns = lodash.filter(buttons, function (o) { return lodash.includes(d.ModuleAssignedButtonIds, o.Id); });
                                    layui.each(assignedBtns, function (index, btn) {
                                        outputHtml += '<input type="checkbox" lay-skin="primary" name="buttonauthorize" lay-filter="modulebtnauthorize" title="' + btn.DisplayName + '" value="' + btn.Id + '"';
                                        if (d.ModuleAuthorizedButtonIds.length > 0 && lodash.indexOf(d.ModuleAuthorizedButtonIds, btn.Id) >= 0) {
                                            outputHtml += " checked />";
                                        } else outputHtml += " />";
                                    });
                                    return outputHtml;
                                } else return '';
                            },
                            singleLine: false
                        }
                    ],
                    data: null
                };
                
            let roleListItmeSwitch = function (othis) {
                $(".list-items li.list-item").removeClass("active");
                othis.addClass("active");
                http.get(backendwebapiConfig.getsystemmodulelistswithauthbyadminrole,
                    { roleId: othis.find("a").data('id')},
                    function () { //beforeSend
                        loading.block({ type: 1, elem: '.right-col-body', msg: '加载中...' })
                    }
                ).done(function (response) {
                    if (response.state && response.state === 200) {
                        const rolemodules = response.data.ModuleModels;
                        buttons = response.data.ModuleButtons;
                        authorizetreetableconfig.data = rolemodules;
                        if (authorizeTableIns === null)
                            authorizeTableIns = treeTable.render(authorizetreetableconfig);
                        else
                            authorizeTableIns.reload(authorizetreetableconfig);
                        authorizeTableIns.expandAll();
                    }
                    else {
                        authorizetreetableconfig.data = null;
                        if (authorizeTableIns === null)
                            authorizeTableIns = treeTable.render(authorizetreetableconfig);
                        else
                            authorizeTableIns.reload(authorizetreetableconfig);
                    }
                }).fail(function (error) {
                    http.ajax.logError(error);
                }).always(function () {
                    loading.blockRemove(".right-col-body", 1000);
                });
            };
            $('#roleslist').on('click', 'li.list-item', function () {
                const othis = $(this);
                roleListItmeSwitch(othis);
            });
            //模块权限开关联动
            form.on('switch(systemmoduleauthorize)', function (data) {
                $("input[name='viewpermission']").removeClass("touched");
                refreshAuthorizeTableStatus($(data.elem));
                form.render();
            });
            const refreshAuthorizeTableStatus = function ($node) {
                //父节点状态影响所有子节点状态
                $node.addClass("touched");
                let nodeCheckStatus = $node.is(":checked");
                if (!nodeCheckStatus) {
                    let $trRow = $node.parents("tr:eq(0)"),
                        $modulebtns = $trRow.find("input[name='buttonauthorize']");
                    if ($modulebtns.length > 0) {
                        $modulebtns.each(function () {
                            //console.log($(this).attr('title'));
                            $(this).prop("checked", false);
                        });
                    }
                }
                let $moduleCheckboxes = $("input[name='viewpermission']"),
                    parents = [], childrens = [], siblings = [],
                    triggerParent = true;
                $moduleCheckboxes.each(function () {
                    let $_ = $(this);
                    if ($_.data("id") !== $node.data("id")) { //排除相同节点
                        if ($_.data("pid") === $node.data("id") && !$_.hasClass("touched")) childrens.push($_);
                        else if ($_.data("id") === $node.data("pid") && !$_.hasClass("touched")) {
                            if (nodeCheckStatus) triggerParent = true;
                            else triggerParent = false;
                            parents.push($_);
                        }
                        else if (!triggerParent && $_.data("pid") === $node.data("pid")) {
                            //siblings 同级节点状态和本节点状态全一致(不勾选)，则触发父节点状态不勾选
                            //         同级节点只要有一个状态为勾选，则父节点状态为勾选
                            siblings.push($_);
                            if (nodeCheckStatus !== $_.is(":checked"))
                                triggerParent = false;
                        }

                        if ($_.data("pid") === $node.data("pid"))
                            $_.addClass("touched");
                    } else if (siblings.length === 0) {
                        //没有同级节点，只有节点自己
                        siblings.push($_);
                    }
                });
                if (childrens.length > 0) {
                    $.each(childrens, function (i, $child) {
                        $child.prop("checked", nodeCheckStatus);
                        refreshAuthorizeTableStatus($child);
                    });
                }
                if (!nodeCheckStatus && siblings.length > 0) {
                    let count = 0;
                    $.each(siblings, function (i, $sibling) {
                        if ($sibling.is(":checked") === nodeCheckStatus)
                            count++;
                    });
                    if (count === siblings.length) triggerParent = true;
                }
                if (triggerParent && parents.length > 0) {
                    $.each(parents, function (i, $parent) {
                        $parent.prop("checked", nodeCheckStatus);
                        refreshAuthorizeTableStatus($parent);
                    });
                }
            };

            //获取系统模块权限数据
            const getModuleAuthorizeData = function () {
                let authorizeList = [],
                    $trRow = null, $modulebtns = null;
                $("input[name='viewpermission']").each(function () {
                    //moduleModel与后端 SystemModuleModel结构相同
                    let moduleModel = {
                        Id: 0,
                        IsActive: false,
                        ModuleAssignedButtonIds: [],
                        ModuleAuthorizedButtonIds: []
                    }, $othis = $(this);
                    moduleModel.Id = PMSUtils.toNumber($othis.data("id"));
                    if ($othis.is(":checked")) moduleModel.IsActive = true;
                    $trRow = $othis.parents("tr:eq(0)");
                    $modulebtns = $trRow.find("input[name='buttonauthorize']");
                    if ($modulebtns.length > 0) {
                        let btnid = 0;
                        $modulebtns.each(function () {
                            const oBtn = $(this);
                            btnid = PMSUtils.toNumber(oBtn.val());
                            moduleModel.ModuleAssignedButtonIds.push(btnid);
                            if (oBtn.is(":checked"))
                                moduleModel.ModuleAuthorizedButtonIds.push(btnid);
                        });
                    }
                    authorizeList.push(moduleModel);
                });
                return authorizeList;
            };
            //监听顶部按钮栏
            treeTable.on('toolbar(pms-table)', function (obj) {
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                if (obj.event === 'OnSave') {
                    const roleId = $("#roleslist li.active").find("a").data("id");
                    if (typeof roleId === "undefined") {
                        popup.failure("请先选择用户角色");
                        return false;
                    }
                    var postData = getModuleAuthorizeData();
                    //console.log(postData);
                    http.post(backendwebapiConfig.updatesystemmoduleauthorize + `?buttonId=${buttonId}&moduleId=${moduleId}&roleId=${roleId}`,
                        postData,
                        function () { //beforeSend
                            loading.block({ type: 1, elem: '.systemauthorizemanage', msg: '数据提交中...' })
                        }
                    ).done(function (response) {
                        if (response.state && response.state === 200) {
                            popup.success(response.message);
                        }
                    }).fail(function (error) {
                        http.ajax.logError(error);
                    }).always(function () {
                        loading.blockRemove(".systemauthorizemanage", 1000);
                    });
                } else if (obj.event === 'OnExpandAll') {
                    authorizeTableIns.expandAll();
                } else if (obj.event === 'OnFoldAll') {
                    authorizeTableIns.foldAll();
                }
            });
        });
    </script>
}
